<template>
  <view class="page">
    <!-- 右上角的规则按钮 -->
    <view class="rule-button" @click="showModal">规则</view>
    
    <!-- 弹窗 -->
    <view v-if="isModalVisible" class="modal-overlay" @click="hideModal">
      <view class="modal" @click.stop>
        <text class="modal-content">本软件是由Dmitai成员的作业，现软件处于试行状态，由于用户的不确定性，所以没有做太多的验证功能，但是后期会做，不仅仅只有虚拟产品，现在注册就是老用户。<br><p></p>老用户1元区直接免费，后期会给你提升用户等级，如果等级为3，9.9及以下的免费，如果等级4，全场免费</text>
        <button class="modal-close" @click="hideModal">关闭</button>
      </view>
    </view>

    <view class="container">
      <!-- 判断用户是否已登录 -->
      <view v-if="isLoggedIn">
        <!-- 登录后的欢迎信息页面 -->
        <view class="welcome-page">
          <text class="welcome-message">欢迎: {{ username }}</text><br>
          <text class="welcome-message">用户等级: {{ leve }} </text><br>
          <text class="welcome-message">余额: ￥{{ balance }} </text>
          <button @click="logout" class="logout-btn">退出登录</button>
        </view>
        
        <!-- 商品展示 -->
        <view class="product-list">
          <view v-for="product in products" :key="product.id" class="product-item">
            <image :src="product.image_url" class="product-image" />
            <text class="product-name">{{ product.name }}</text>
            <text class="product-price">￥{{ product.price }}</text>
            <button v-if="isLoggedIn && product.price != '0.00'" class="purchase-btn" @click="purchase(product)">立即购买</button>
            <text v-else class="not-logged-in-message">登录后可购买</text>
          </view>
        </view>
      </view>

      <!-- 登录和注册表单 -->
      <view v-else>
        <view v-if="isLogin" class="form">
          <view class="input-group">
            <text class="label">用户名</text>
            <input v-model="username" class="input" type="text" placeholder="请输入用户名" />
          </view>

          <view class="input-group">
            <text class="label">密码</text>
            <input v-model="password" class="input" type="password" placeholder="请输入密码" />
          </view>

          <button class="login-btn" @click="handleLogin">登录</button>
          
          <view v-if="errorMessage" class="error-message">
            <text>{{ errorMessage }}</text>
          </view>

          <view class="switch-auth">
            <text @click="toggleAuth">没有账号? 注册</text>
          </view>
        </view>

        <!-- 注册表单 -->
        <view v-else class="form">
          <view class="input-group">
            <text class="label">用户名</text>
            <input v-model="username" class="input" type="text" placeholder="请输入用户名" />
          </view>

          <view class="input-group">
            <text class="label">密码</text>
            <input v-model="password" class="input" type="password" placeholder="请输入密码" />
          </view>

          <button class="register-btn" @click="handleRegister">注册</button>

          <view v-if="errorMessage" class="error-message">
            <text>{{ errorMessage }}</text>
          </view>

          <view class="switch-auth">
            <text @click="toggleAuth">已有账号? 登录</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isModalVisible: false, 
      errorMessage: '',  
      username: '',  
      password: '',  
      isLogin: true,  
      isLoggedIn: false,  
      leve: '',  
      banStatus: false,  
      banMessage: '',  
      balance: 0,  
      loginInterval: null,  
      products: [],  
    };
  },
  
  computed: {
    storedUsername() {
      return uni.getStorageSync('username');
    }
  },
  
  watch: {
    storedUsername(newVal) {
      this.isLoggedIn = !!newVal;
      this.username = newVal || '';  
    }
  },
  
  methods: {
    showModal() {
      this.isModalVisible = true;
    },
    
    hideModal() {
      this.isModalVisible = false;
    },

    handleLogin() {
      this.errorMessage = '';
    
      if (!this.username || !this.password) {
        this.errorMessage = '用户名和密码不能为空';
        return;
      }
    
      uni.request({
        url: 'http://localhost:3000/login',
        method: 'POST',
        data: { username: this.username, password: this.password },
        success: (res) => {
          if (res.data.success) {
            uni.setStorageSync('token', res.data.token);
            uni.setStorageSync('username', this.username);
            this.username = this.username;
            this.isLoggedIn = true;
            this.fetchUserLevel();
            this.fetchUserStatus();
            this.fetchUserBalance();
            this.errorMessage = '';
            uni.showToast({ title: '登录成功', icon: 'success', duration: 2000 });
          } else {
            this.errorMessage = res.data.message || '登录失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    fetchUserLevel() {
      uni.request({
        url: 'http://localhost:3000/getUserLevel',
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          this.leve = res.data.success ? res.data.level : '未知';
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.leve = '未知';
        }
      });
    },

    fetchUserStatus() {
      uni.request({
        url: 'http://localhost:3000/getUserStatus',
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          if (res.data.success) {
            if (res.data.isBanned) {
              this.banStatus = true;
              this.banMessage = res.data.describews || '你已被封号，请联系管理员';
              this.errorMessage = this.banMessage;
              this.logout();
              uni.showModal({
                title: '封号通知',
                content: this.banMessage,
                showCancel: false,
                confirmText: '知道了',
                success: () => {
                  uni.redirectTo({ url: '/pages/login/login' });
                }
              });
            } else {
              this.banStatus = false;
              this.banMessage = '';
              this.errorMessage = '';
            }
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    fetchUserBalance() {
      uni.request({
        url: 'http://localhost:3000/getUserBalance',
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          this.balance = res.data.success ? res.data.balance : 0;
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.balance = 0;
        }
      });
    },

    handleRegister() {
      this.errorMessage = '';
      if (!this.username || !this.password) {
        this.errorMessage = '用户名和密码不能为空';
        return;
      }

      uni.request({
        url: 'http://localhost:3000/register',
        method: 'POST',
        data: { username: this.username, password: this.password },
        success: (res) => {
          if (res.data.success) {
            uni.showToast({ title: '注册成功', icon: 'success' });
            this.toggleAuth();
          } else {
            this.errorMessage = res.data.message || '注册失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    toggleAuth() {
      this.isLogin = !this.isLogin;
      this.username = '';
      this.password = '';
      this.errorMessage = '';
    },

    logout() {
      uni.removeStorageSync('token');
      uni.removeStorageSync('username');
      uni.showToast({ title: '退出成功', icon: 'success' });
      this.isLoggedIn = false;
    },

    checkLoginStatus() {
      this.loginInterval = setInterval(() => {
        const storedUsername = uni.getStorageSync('username');
        this.isLoggedIn = !!storedUsername;
        this.username = storedUsername || '';
        if (this.isLoggedIn) {
          this.fetchUserLevel();
          this.fetchUserStatus();
          this.fetchUserBalance();
        }
      }, 10000);
    },

    fetchProducts() {
      uni.request({
        url: 'http://localhost:3000/products',
        method: 'GET',
        success: (res) => {
          this.products = res.data.success ? res.data.products : [];
        },
        fail: (err) => {
          console.error('请求失败:', err);
        }
      });
    },

    purchase(product) {
      // Logic to handle product purchase
      if (this.balance >= parseFloat(product.price)) {
        uni.showToast({
          title: `成功购买: ${product.name}`,
          icon: 'success',
          duration: 2000
        });
      } else {
        uni.showToast({
          title: '余额不足',
          icon: 'none',
          duration: 2000
        });
      }
    }
  },

  mounted() {
    const storedUsername = uni.getStorageSync('username');
    this.username = storedUsername || '';
    this.isLoggedIn = !!storedUsername;
    if (this.isLoggedIn) {
      this.fetchUserLevel();
      this.fetchUserStatus();
      this.fetchUserBalance();
    }

    this.checkLoginStatus();
    this.fetchProducts();
  },

  beforeDestroy() {
    if (this.loginInterval) {
      clearInterval(this.loginInterval);
    }
  }
}
</script>

<style scoped>
/* 整个页面 */
.page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #F2F2F2;  /* 背景色为淡灰色 */
  height: 100vh;
  overflow: hidden;
  font-family: 'Helvetica Neue', sans-serif;
}


/* 登录、注册表单 */
.form {
  background: rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(8px);
  border-radius: 16px;
  padding: 30px;
  width: 85%;
  max-width: 350px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

/* 输入框 */
.input-group {
  margin-bottom: 20px;
  position: relative;
}

.input-group .label {
  font-size: 16px;
  color: #6E7E77;  /* 柔和灰绿色 */
  margin-bottom: 8px;
  font-weight: 500;
}

.input {
  width: 95%;
  padding: 15px;
  font-size: 16px;
  color: #4B4F4F;  /* 深灰色 */
  background: rgba(255, 255, 255, 0.6);
  border: none;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.input:focus {
  outline: none;
  border: 2px solid #7C9A92;  /* 灰绿色焦点边框 */
}

.login-btn, .register-btn {
  width: 100%;
  padding: 14px;
  font-size: 18px;
  color: #FFF;
  background-color: #7C9A92;  /* 莫兰迪色调的灰绿色 */
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-btn:hover, .register-btn:hover {
  background-color: #A1B7AE;  /* 灰绿色的浅色调 */
}

.error-message {
  color: #FF5C5C;  /* 错误提示颜色 */
  font-size: 14px;
  margin-top: 10px;
}

.switch-auth {
  margin-top: 10px;
  font-size: 14px;
  color: #6E7E77;
  text-align: center;
  cursor: pointer;
}

.switch-auth:hover {
  color: #7C9A92;  /* 鼠标悬停时更亮的颜色 */
}

/* 欢迎页面 */
.welcome-page {
  background: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 30px;
  width: 100%;
  max-width: 450px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.welcome-message {
  font-size: 18px;
  color: #6E7E77;
  margin-bottom: 10px;
  font-weight: 600;
}

.logout-btn {
  background-color: #E6A7A1;  /* 莫兰迪色调的粉色调 */
  color: white;
  padding: 12px 20px;
  border-radius: 12px;
  font-size: 16px;
  cursor: pointer;
  border: none;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background-color: #FF5C5C;
}

/* 商品列表 */
.product-list {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  width: 100%;
}

.product-item {
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(8px);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
  text-align: center;
  transition: all 0.3s ease;
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.2);
}

.product-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 10px;
}

.product-name {
  font-size: 18px;
  color: #6E7E77;
  margin-top: 10px;
}

.product-price {
  font-size: 20px;
  color: #E6A7A1;
  margin-top: 5px;
}

.purchase-btn {
  background-color: #7C9A92;
  color: white;
  padding: 12px 20px;
  border-radius: 12px;
  margin-top: 10px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.purchase-btn:hover {
  background-color: #A1B7AE;
}

.not-logged-in-message {
  color: #A1A1A1;
  margin-top: 10px;
  font-size: 14px;
}

/* 弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal {
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(15px);
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  width: 80%;
  max-width: 500px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.modal-content {
  font-size: 16px;
  color: #6E7E77;
  margin-bottom: 20px;
}

.modal-close {
  padding: 10px 20px;
  background-color: #7C9A92;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
}

.modal-close:hover {
  background-color: #A1B7AE;
}

/* 规则按钮 */
.rule-button {
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: #E6A7A1;
  color: white;
  padding: 12px 20px;
  border-radius: 30px;
  font-size: 14px;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.rule-button:hover {
  background-color: #FF5C5C;
}

</style>
